package com.feng.study.demo.sort;

import com.feng.study.model.Product;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.function.ToIntFunction;

/**
 * 排序应用
 */
public class SortUse {
    public static void main(String[] args) {
        ArrayList<String> arrayList = Lists.newArrayList("111", "112");
        Product product1 = new Product().setProductId("111").setNum(12).setPrice("1230");
        Product product2 = new Product().setProductId("112").setNum(12).setPrice("1238");
        Product product3 = new Product().setProductId("110").setNum(11).setPrice("1234").setName("aaa");
        ArrayList<Product> products= Lists.newArrayList(product1,product2,product3);

        //以arrayList数组中的顺序，products列表中的数据对productId字段排序
        products.sort(Comparator.comparingInt(p->arrayList.indexOf(p.getProductId())));
        //这个对上面lambda表达式写法的补充，方便理解（理解这个主要还是阅读TimSortDemo中TimSort的底层源码阅读
        products.sort(new TestComparator());

        //没有在arrayList数组中的排到最后面
        products.sort(Comparator.comparing(
                Product::getProductId, (s1, s2) -> {
                    Integer index1 = !arrayList.contains(s1) ? arrayList.size() : arrayList.indexOf(s1);
                    Integer index2 = !arrayList.contains(s2) ? arrayList.size() : arrayList.indexOf(s2);
                    return index2.compareTo(index1);
                }));
        products.sort((s1, s2) -> {
            Integer index1 = !arrayList.contains(s1.getProductId()) ? arrayList.size() : arrayList.indexOf(s1.getProductId());
            Integer index2 = !arrayList.contains(s2.getProductId()) ? arrayList.size() : arrayList.indexOf(s2.getProductId());
            return index2.compareTo(index1);
        });

        System.out.println(products);

        //先按productId升序排序，再按price降序排序
        products.sort(Comparator.comparing(Product::getProductId).thenComparing(Product::getPrice,Comparator.reverseOrder()));
//        products.sort(Comparator.comparing(Product::getProductId).thenComparing(p->p.getPrice(),Comparator.nullsLast()));
        System.out.println(products);
    }
}


class TestToIntFunction implements ToIntFunction<Product> {
    ArrayList<String> sortList = Lists.newArrayList("112", "113", "111","115","116");
    @Override
    public int applyAsInt(Product value) {
        return sortList.indexOf(value.getProductId());
    }
}
class TestComparator implements Comparator<Product> {
    TestToIntFunction test = new TestToIntFunction();

    @Override
    public int compare(Product o1, Product o2) {
        return Integer.compare(test.applyAsInt(o1), test.applyAsInt(o2));
    }
}